<?php

namespace App\Http\Controllers\Admin;
use Hash;
use Illuminate\Http\Request;
use App\Http\Requests\UserRequest;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
class UserController extends Controller
{
    /*
        显示后台用户添加页面
    */
    
    public function getAdd(){
        //解析模板
        return view('Admin.user.add');
    }

    /*
        接收提交的数据 进行添加    
    */        
    public function postInsert(UserRequest $request){
        //处理数据
        // dd($request);
        $data = $request->only(['username','password','email','phone']);
        // dd($data);
        $data['token'] = str_random(50);
        // $data['phone'] = '333390';
        // //密码加密
        // dd($data['phone']);
        $data['password'] = Hash::make($data['password']);
        // dd($data);
        $res = DB::table('user')->insert($data);
        // dd($res);
        if($res){
            return redirect('/admin/user/index')->with('success','用户添加成功');
        }else{
            return back()->with('error','用户添加失败'); 
        }     


        // dd($data);
    }  

    //显示用户列表
    public function getIndex(Request $request){

    	// var_dump($request->all());
    	//获取显示条数
    	$num = $request->input('num',10);
    	//判断是否有关键字
    	if($request->input('keywords')){
    		$users = DB::table('user')
    		->where('username','like','%'.$request->input('keywords').'%')
    		->paginate($num);
    	}else{
    		
        $users = DB::table('user')->paginate($num);
    	}
       	$data = $request->all();
        // dd($users);
        //解析模板
        return view('admin.user.index',['users'=>$users,'data'=>$data]);
    }


    //用户的删除
    public function getDelete($id){
        // dd($id);
        $res = DB::table('user')->where('id',$id)->delete();
        if($res){
            return redirect('/admin/user/index')->with('success','用户删除成功');
        }else{
            return back()->with('error','用户删除失败'); 
        }  
    }

    //用户的修改
    public function getEdit($id){
    	$res = DB::table('user')->where('id',$id)->first();
    	// dd($res);
    	//解析模板
    	return view('admin.user.edit',['userinfo'=>$res]);
    }

    //执行用户修改
    public function postUpdate(Request $request){
    	// dd($request);
    	$id = $request->input('id');
    	$data = $request->only(['username','email','phone']);
    	// dd($data);
    	$res = DB::table('user')->where('id',$id)->update($data);
    	if($res){
            return redirect('/admin/user/index')->with('success','用户修改成功');
        }else{
            return back()->with('error','用户修改失败'); 
        }  
    }

}
